import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertest/utils/helper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'screens/login_screen.dart';
import 'screens/home_screen.dart';
import 'services/heartbeat_service.dart';
import 'utils/http_client.dart';

final heartbeatService = HeartbeatService();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化网络客户端
  HttpClient.init(GlobalKey<ScaffoldMessengerState>());
  await HttpClient.initInterceptors();

  // 初始化心跳服务
  await heartbeatService.init();

  // 检查是否已登录
  final prefs = await SharedPreferences.getInstance();
  final token = prefs.getString('token');
  final isAutoLogin = prefs.getBool('autoLogin') ?? false;
  final loginTimeStr = prefs.getString('loginTime');

  bool isValidLogin = false;
  if (token != null && isAutoLogin && loginTimeStr != null) {
    final loginTime = DateTime.parse(loginTimeStr);
    final now = DateTime.now();
    final difference = now.difference(loginTime);

    // 检查是否在30天有效期内
    if (difference.inDays < 30) {
      isValidLogin = true;
    } else {
      // 超过30天，清除登录信息
      await prefs.remove('token');
      await prefs.remove('savedJobNumber');
      await prefs.remove('savedPassword');
      await prefs.remove('loginTime');
      await prefs.remove('userInfo');
      await prefs.setBool('autoLogin', false);
    }
  }

  if (isValidLogin) {
    heartbeatService.startHeartbeat();
  }

  runApp(MyApp(isLoggedIn: isValidLogin));
}

class MyApp extends StatelessWidget {
  final bool isLoggedIn;

  const MyApp({
    super.key,
    required this.isLoggedIn,
  });

  @override
  Widget build(BuildContext context) {
    String version = "2.1.15";
    return MaterialApp(
      title: '金虎送货',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.orange),
        useMaterial3: true,
      ),
      home: isLoggedIn ? const HomeScreen() : LoginScreen(version: version,),
      routes: Helper.typeNameMap({
          HomeScreen:(_)=>const HomeScreen(),
          LoginScreen:(_)=>LoginScreen(version: version,),
        }),
    );
  }
} 